package com.xiangban.yanglaodajie_platform.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xiangban.yanglaodajie_platform.dao.ClassOrActivityMapper;
import com.xiangban.yanglaodajie_platform.dao.ClassifyGoodsMapper;
import com.xiangban.yanglaodajie_platform.dao.OrdersClassOrActivityMapper;
import com.xiangban.yanglaodajie_platform.dao.UserMapper;
import com.xiangban.yanglaodajie_platform.entity.*;
import com.xiangban.yanglaodajie_platform.entity.dto.*;
import com.xiangban.yanglaodajie_platform.entity.res.ApiResultCode;
import com.xiangban.yanglaodajie_platform.exception.BizException;
import com.xiangban.yanglaodajie_platform.utils.CommonUtils;
import com.xiangban.yanglaodajie_platform.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

import static com.xiangban.yanglaodajie_platform.utils.CommonUtils.BizEmpty;
import static com.xiangban.yanglaodajie_platform.utils.CommonUtils.compare;
import static com.xiangban.yanglaodajie_platform.utils.DateUtil.getNowDateTime;
import static com.xiangban.yanglaodajie_platform.utils.DateUtil.getStringTimestamp;

/**
 * @Author Mr. MaYaYun
 * @Data 2021/5/8 14:11
 */
@Service
public class ClassOrActivityService {

    @Autowired
    private ClassOrActivityMapper classOrActivityMapper;
    @Autowired
    private CommonUtils commonUtils;
    @Autowired
    private ClassifyGoodsMapper classifyGoodsMapper;
    @Autowired
    private OrdersClassOrActivityMapper ordersClassOrActivityMapper;
    @Autowired
    private OrdersClassOrActivityService ordersClassOrActivityService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserMapper userMapper;

    //活动列表(树状)
    public Object getList(ClassOrActivity classOrActivity) {//商家Id
        if (BizEmpty(classOrActivity.getShopId())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        ClassifyGoods goods = new ClassifyGoods();
        goods.setShopId(classOrActivity.getShopId());
        List<ClassifyGoods> list = classifyGoodsMapper.getList(goods);//查询出所有分类

        ArrayList<Map<String, Object>> maps = new ArrayList<>();
        for (ClassifyGoods classifyGoods : list) {
            HashMap<String, Object> map1 = new LinkedHashMap<>();
            classOrActivity.setClassifyGoodsId(classifyGoods.getId());//设置分类id
            List<ClassOrActivityDto> activity = classOrActivityMapper.findActivity(classOrActivity);//根据商家id和分类id查询出活动
            if (commonUtils.getUserId(request) != null) {
                ArrayList<Object> list1 = new ArrayList<>();
                if (activity.size() > 0) {
                    map1.put("id", classifyGoods.getId());
                    map1.put("classifyName", classifyGoods.getClassifyName());
                    for (ClassOrActivityDto classOrActivityDto : activity) {
                        OrdersClassOrActivity ordersClassOrActivity = new OrdersClassOrActivity();
                        ordersClassOrActivity.setUserId(Integer.parseInt(commonUtils.getUserId(request)));
                        ordersClassOrActivity.setClassOrActivityId(classOrActivityDto.getId());
                        OrdersClassOrActivity orders = ordersClassOrActivityMapper.findOrdersByUserIdAndClassOrActivityId(ordersClassOrActivity);
                        if (orders != null) {
                            classOrActivityDto.setIsApply(1);
                        } else {
                            classOrActivityDto.setIsApply(-1);
                        }
                        Date date = new Date();
                        Date endTime = classOrActivityDto.getEndTime();
                        if (date.getTime() < endTime.getTime()) {
                            list1.add(classOrActivityDto);
                        }
                    }
                    map1.put("data", list1);
                }

                maps.add(map1);
            } else {
//                     for (ClassOrActivityDto classOrActivityDto : activity) {
//                         classOrActivityDto.setIsApply(-1);
//                     }
                if (activity.size() > 0) {
                    map1.put("id", classifyGoods.getId());
                    map1.put("classifyName", classifyGoods.getClassifyName());
                    ArrayList<Object> list1 = new ArrayList<>();
                    for (ClassOrActivityDto classOrActivityDto : activity) {
                        classOrActivityDto.setIsApply(-1);
                        Date date = new Date();
                        Date endTime = classOrActivityDto.getEndTime();
                        if (date.getTime() < endTime.getTime()) {
                            list1.add(classOrActivityDto);
                        }
                    }
                    map1.put("data", list1);
                    maps.add(map1);
                }
            }

        }
        return maps;
    }

    public ClassOrActivityDto getInfo(ClassOrActivityDto classOrActivityDto) throws ParseException {//参数:用户id：user_id,活动id：id
        if (BizEmpty(classOrActivityDto.getId())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        ClassOrActivityDto info = classOrActivityMapper.findInfo(classOrActivityDto);//活动详情
        //TODO 任课教师
        List<Object> teacher = getTeacher(classOrActivityDto);
        if (teacher.size() > 0) {
            info.setActivityTeacher(teacher);
        }
        //TODO 教材介绍
        Map<String, Object> classMaterials = getClassMaterials(classOrActivityDto.getId());
        if (classMaterials.keySet().size() > 0) {
            info.setClassMaterials(classMaterials);
        }
        //TODO 教学大纲
        List<String> classOutline = getClassOutline(classOrActivityDto.getId());
        if (classOutline.size() > 0) {
            info.setClassOutline(classOutline);
        }
        //TODO 教学进度
        List<Object> classProgress = getClassProgress(classOrActivityDto.getId());
        if (classProgress.size()>0){
            info.setClassProgress(classProgress);
        }


        //TODO 上课时间
        List<ClassSchedule> classSchedule1 = classOrActivityMapper.findClassSchedule(classOrActivityDto);
        List<DateDto> dateDtos = new ArrayList<>();
        for (ClassSchedule classSchedule : classSchedule1) {
            List<DateDto> dateDtos1 = JSON.parseArray(classSchedule.getAttendTime(), DateDto.class);
            for (DateDto dateDto : dateDtos1) {
                dateDto.setWeek(numberToWeek(classSchedule.getWeek()));
                dateDtos.add(dateDto);
            }
        }
        info.setAttendTime(dateDtos);

        //已登录
        if (commonUtils.getUserId(request) != null) {
            int userId = Integer.parseInt(commonUtils.getUserId(request));
            classOrActivityDto.setUserId(userId);

            OrdersClassOrActivity ordersClassOrActivity = new OrdersClassOrActivity();
            ordersClassOrActivity.setUserId(classOrActivityDto.getUserId());
            ordersClassOrActivity.setClassOrActivityId(classOrActivityDto.getId());
            //是否能在订单里查到是否报名此活动
            OrdersClassOrActivity orders = ordersClassOrActivityMapper.findOrdersByUserIdAndClassOrActivityId(ordersClassOrActivity);
            int weekOfDate = DateUtil.getWeekOfDate(new Date());
            ClassSchedule classSchedule = new ClassSchedule();
            classSchedule.setWeek(weekOfDate);
            classSchedule.setClassOrActivityId(classOrActivityDto.getId());
            ClassSchedule classScheduleRes = ordersClassOrActivityMapper.getClassSchedule(classSchedule);
            SignParameter signParameter = new SignParameter();
            if (classScheduleRes != null) {
                String attendTime = classScheduleRes.getAttendTime();
                List<DateDto> jsonArray = JSONArray.parseArray(attendTime, DateDto.class);
                signParameter = ordersClassOrActivityService.judgeSign(jsonArray, userId, classOrActivityDto.getId());
                info.setIsSign(1); //签退
                if (signParameter.isSign()) {
                    info.setIsSign(0); //签到
                }
            } else {
                info.setIsSign(2); //无课程
            }
            if (orders != null) {
                info.setIsApply(1);
            } else {
                info.setIsApply(-1);//未报名
            }
        } else {
            //未登录
            info.setIsApply(-1);//未报名
        }


        return info;
    }

    private List<Object> getTeacher(ClassOrActivityDto classOrActivityDto) {
        ArrayList<Object> list = new ArrayList<>();

        //查询教师信息
        List<TeacherShopDto> teacher = classOrActivityMapper.selectClassActivityTeacher(classOrActivityDto);
        if (!BizEmpty(teacher)) {
            for (int i = 0; i < teacher.size(); i++) {
                HashMap<String, Object> map = new HashMap<>();
                if (teacher.get(i).getTeacherId() != null) {
                    TeacherShopDto teacherShopDto = classOrActivityMapper.selectActivityTeacherInfo(teacher.get(i).getTeacherId());
                    map.put("teacherId", teacher.get(i).getTeacherId());
                    map.put("teacherName", teacherShopDto.getTeacherName());
                    map.put("teacherImage", teacherShopDto.getTeacherImage());
                    map.put("teacherRole", teacher.get(i).getRole());
                }
                if (teacher.get(i).getSquadId() != null) {
                    UserDto user = new UserDto();
                    user.setUserId(teacher.get(i).getSquadId());
                    UserDto userInfoById = userMapper.getUserInfoById(user);
                    map.put("squadId", teacher.get(i).getTeacherName());
                    map.put("teacherName", userInfoById.getNickName());
                    map.put("teacherImage", userInfoById.getImage());
                    map.put("teacherRole", teacher.get(i).getRole());
                }
                list.add(map);
            }
        }
        return list;
    }

    private Map<String, Object> getClassMaterials(Integer id) {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        //查询课程教材
        ClassMaterials classMaterials = classOrActivityMapper.selectClassMaterials(id);
        if (classMaterials != null) {
            JSONArray objects = JSON.parseArray(classMaterials.getImage());
            map.put("text", classMaterials.getText());
            map.put("images", objects);
        }
        return map;
    }

    private List<String> getClassOutline(Integer id) {
        ArrayList<String> list = new ArrayList<>();
        //查询教学大纲
        List<ClassOutline> classOutlines = classOrActivityMapper.selectOutlineList(id);
        if (classOutlines.size() > 0) {
            for (ClassOutline classOutline : classOutlines) {
                list.add(classOutline.getText());
            }
        }
        return list;
    }

    private List<Object> getClassProgress(Integer id){
        ArrayList<Object> list = new ArrayList<>();
        //查询教学进度
        List<ClassProgress> classProgresses = classOrActivityMapper.selectClassProgressList(id);
        if (classProgresses.size()>0){
            for (ClassProgress classProgress : classProgresses) {
                HashMap<String, Object> map = new HashMap<>();
                int stringTimestamp = Integer.parseInt(getStringTimestamp(getNowDateTime()));//当前时间戳
                String end_time = classProgress.getEndTime();
                int stringTimestamp1 = Integer.parseInt(getStringTimestamp(end_time));//上课结束时间戳
                if (stringTimestamp >stringTimestamp1){
                    map.put("flag","0");//0:已结束 1:未开始
                }else {
                    map.put("flag","1");
                }
                map.put("title",classProgress.getTitle());
                map.put("outline",classProgress.getOutline());
                map.put("start_time",classProgress.getStartTime());
                map.put("end_time",classProgress.getEndTime());
                list.add(map);
            }
        }
        return list;
    }

    public String numberToWeek(Integer number) {
        switch (number) {
            case 1:
                return "星期一";
            case 2:
                return "星期二";
            case 3:
                return "星期三";
            case 4:
                return "星期四";
            case 5:
                return "星期五";
            case 6:
                return "星期六";
            case 7:
                return "星期日";
            default:
                return "";
        }
    }
}
